from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from .models import City, DataCenter, Host, HostPassword, DailyStat
from .ser import CitySerializer, DataCenterSerializer, HostSerializer, HostPasswordSerializer, DailyStatSerializer
import subprocess
from django.utils import timezone
import random
import string


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class DataCenterViewSet(viewsets.ModelViewSet):
    queryset = DataCenter.objects.all()
    serializer_class = DataCenterSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def check_ping(self, request, pk=None):
        host = self.get_object()
        try:
            # For Linux/MacOS
            if host.os_type in ['linux', 'macos']:
                result = subprocess.run(['ping', '-c', '1', host.ip_address],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        timeout=5)
            # For Windows
            else:
                result = subprocess.run(['ping', '-n', '1', host.ip_address],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        timeout=5)

            is_reachable = result.returncode == 0
            return Response({
                'host': host.hostname,
                'ip_address': host.ip_address,
                'is_reachable': is_reachable,
                'ping_output': result.stdout.decode('utf-8')
            })
        except subprocess.TimeoutExpired:
            return Response({
                'host': host.hostname,
                'ip_address': host.ip_address,
                'is_reachable': False,
                'ping_output': 'Request timed out'
            }, status=status.HTTP_408_REQUEST_TIMEOUT)


class HostPasswordViewSet(viewsets.ModelViewSet):
    queryset = HostPassword.objects.all()
    serializer_class = HostPasswordSerializer

    def generate_random_password(self):
        length = 16
        chars = string.ascii_letters + string.digits + '!@#$%^&*'
        return ''.join(random.choice(chars) for _ in range(length))

    def perform_update(self, serializer):
        host_password = self.get_object()
        # Save old password to history
        history = host_password.history or []
        history.append({
            'password': host_password.root_password,
            'changed_at': timezone.now().isoformat()
        })
        # Generate new password
        new_password = self.generate_random_password()
        serializer.save(root_password=new_password, history=history[:10])  # Keep last 10 passwords


class DailyStatViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = DailyStat.objects.all()
    serializer_class = DailyStatSerializer
    filterset_fields = ['date', 'city', 'data_center']
